package com.hctforgreen.greenservice.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class BookZipTxtReaderUtil {

	public static String readTxt(String filePath, String bookId)
			throws Exception {

		String dePath = UnZipUtil.getDeCompressionFilePath(filePath);
		
		UnZipUtil.deCompressionZipFile(filePath, dePath);
//		String sJson = readTxtInZip(new File(filePath), bookId);

		String sJson = readTxtInDePath(dePath, bookId);
		return sJson;
	}

	public static String readTxtInDePath(String dePath, String bookId) {
		String sJson = "";
		try {
			String txtPath = dePath + "/" + bookId.toUpperCase() + ".txt";
			FileInputStream in = new FileInputStream(txtPath);
			// ====================

			InputStreamReader isr = new InputStreamReader(in, "GBK");
			BufferedReader br = new BufferedReader(isr);
			
			String line; 
			while ( (line = br.readLine()) != null) {
				sJson += line;
			}
			in.close();
			isr.close();
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				/**
				 * 还在考虑是否把close操作移动到这里
				 */
			} catch (Exception e) {
			}
		}
		return sJson;

	}
	public static String readTxtInZip(File thefile, String bookId) {
		String sJson = "";
		try {
			ZipFile zip = new ZipFile(thefile);
			// "2C90808A453F783E01453F85F3A90674.txt"
			ZipEntry entry = zip.getEntry(bookId.toUpperCase() + ".txt");
			InputStream in  = zip.getInputStream(entry);

			// ====================

			InputStreamReader isr = new InputStreamReader(in, "GBK");
			BufferedReader br = new BufferedReader(isr);
			
			String line; 
			while ( (line = br.readLine()) != null) {
				sJson += line;
			}
			in.close();
			isr.close();
			br.close();
			zip.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				/**
				 * 还在考虑是否把close操作移动到这里
				 */
			} catch (Exception e) {
			}
		}
		return sJson;

	}

}
